//
//  RegisterViewController.m
//  NewPro
//
//  Created by 何荧红 on 2018/10/16.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "RegisterViewController.h"
#import "addAdressCell.h"
#import "APPAgreementVC.h"
#import "LoginStore.h"

@interface RegisterViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UserDefaultsManager *userManager;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *realname;
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *passWord;
@property (nonatomic, copy) NSString *rePassWord;
@property (nonatomic, copy) NSString *phoneName;
@property (nonatomic, copy) NSString *realPhone;
@property (nonatomic, copy) NSString *realCode;
@property (nonatomic, copy) NSString *code;

@property (nonatomic, assign) BOOL SureRegister;

@end

@implementation RegisterViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self CleanSubView];
}
- (void)CleanSubView{
    self.userManager = [UserDefaultsManager sharedInstance];
    self.SureRegister = NO;
    self.view.backgroundColor = [UIColor colorWithHexString:@"F4F4F4"];
    ViewHeader *header = [[ViewHeader alloc]initWithDefaultString:@"注册"];
    [self.view addSubview:header];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, iPhoneX_Top, SCREEN_WIDTH, 250) style:UITableViewStyleGrouped];
    _tableView.scrollEnabled = NO;
    [_tableView registerNib:[UINib nibWithNibName:@"addAdressCell" bundle:nil] forCellReuseIdentifier:@"addAdressCellID"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    UIButton *iconimg = [[UIButton alloc]init];
    [iconimg addTarget:self action:@selector(buttonClik:) forControlEvents:UIControlEventTouchUpInside];
    [iconimg setImage:[UIImage imageNamed:@"注册确认空圈"] forState:UIControlStateNormal];
    [self.view addSubview:iconimg];
    [iconimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom).offset(0);
        make.left.equalTo(self.view.mas_left).offset(9);
        make.height.mas_equalTo(22);
        make.width.mas_equalTo(22);
    }];
    UILabel *cansure = [[UILabel alloc]init];
    cansure.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    cansure.textColor = [UIColor colorWithHexString:@"666666"];
    cansure.text = @"我已阅读并同意";
    [self.view addSubview:cansure];
    [cansure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(iconimg.mas_centerY);
        make.left.equalTo(iconimg.mas_right).offset(0);
    }];
    UIButton *Agreement = [[UIButton alloc]init];
    Agreement.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    [Agreement setTitle:@"《畅享合伙人合作协议及营销规范》" forState:UIControlStateNormal];
    [Agreement setTitleColor:[UIColor colorWithHexString:@"0CA6F0"] forState:UIControlStateNormal];
    [Agreement addTarget:self action:@selector(toappinfo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:Agreement];
    [Agreement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(33);
        make.left.equalTo(cansure.mas_right);
        make.centerY.equalTo(cansure.mas_centerY);
    }];
    UIView *blueline = [[UIView alloc]init];
    blueline.backgroundColor = [UIColor colorWithHexString:@"0CA6F0"];
    [self.view insertSubview:blueline belowSubview:Agreement];
    [blueline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1);
        make.left.equalTo(Agreement.mas_left);
        make.right.equalTo(Agreement.mas_right);
        make.top.equalTo(Agreement.mas_bottom).offset(-11);
    }];
    UIButton *tosure = [[UIButton alloc]init];
    tosure.layer.cornerRadius = 5;
    tosure.backgroundColor = [UIColor colorWithHexString:@"0CA6F0"];
    tosure.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:18];
    [tosure setTitle:@"注册" forState:UIControlStateNormal];
    [tosure setTitleColor:[UIColor colorWithHexString:@"FFFFFF"] forState:UIControlStateNormal];
    [tosure addTarget:self action:@selector(tosure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tosure];
    [tosure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(49);
        make.left.equalTo(self.view.mas_left).offset(14);
        make.right.equalTo(self.view.mas_right).offset(-14);
        make.top.equalTo(iconimg.mas_bottom).offset(65);
    }];
}
- (void)buttonClik:(UIButton *)button{
    button.selected = !button.selected;
    if (button.selected) {
        self.SureRegister = YES;
        [button setImage:[UIImage imageNamed:@"注册确认"] forState:UIControlStateNormal];
    }else{
        self.SureRegister = NO;
        [button setImage:[UIImage imageNamed:@"注册确认空圈"] forState:UIControlStateNormal];
    }
}
- (void)toappinfo{
    APPAgreementVC *VC = [[APPAgreementVC alloc]init];
    [[AppDelegate sharedAppDelegate] pushViewController:VC];
}
- (void)tosure{
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *prams = [[NSMutableDictionary alloc]init];
    if (self.SureRegister) {
        if (self.userName.length > 0) {
            [prams setObject:self.userName forKey:@"realName"];
            if ([self.phoneName isVaildMobileNo]) {
                if ((self.realPhone && [self.phoneName isEqualToString:self.realPhone]) || !self.realPhone) {
                [prams setObject:self.phoneName forKey:@"userName"];
                if (self.code.length > 0) {
                    if ([self.code isEqualToString:self.realCode]) {
                        if (self.passWord.length > 0) {
                            if (self.rePassWord.length > 0) {
                                if ([self.rePassWord isEqualToString:self.passWord]) {
                                    [prams setObject:[self.passWord stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"passWord"];
                                    [prams setObject:[self.rePassWord stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"rePassWord"];
                                    [self registerWith:prams];
                                }else{
                                    [self showMBPError:@"新密码和确认密码不一致"];
                                }
                            }else{
                                [self showMBPError:@"请再次输入密码"];
                            }
                        }else{
                            [self showMBPError:@"请输入密码"];
                        }
                    }else{
                        [self showMBPError:@"请输入正确的验证码"];
                    }
                }else{
                    [self showMBPError:@"请输入验证码"];
                }
                }else{
                    [self showMBPError:@"手机号与获取验证码手机号不一致"];
                }
            }else{
                [self showMBPError:@"请输入真实手机号"];
            }
        }else{
            [self showMBPError:@"请输入真实姓名"];
        }
    }else{
        [self showMBPError:@"未同意协议"];
    }
}
- (void)registerWith:(NSDictionary *)dic{
    [[[LoginStore alloc]init] RegisterWithPrams:dic Success:^(NSString * _Nonnull code) {
        if ([code isEqualToString:@"success"]) {
            [self showMBPError:@"注册成功"];
            [self performSelectorOnMainThread:@selector(PopBack) withObject:nil waitUntilDone:0.3f];
        }else{
            [self showMBPError:code];
        }
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
- (void)PopBack{
    [[AppDelegate sharedAppDelegate] popViewController];
}

- (void)back{
    [[AppDelegate sharedAppDelegate] popViewController];
}
- (void)sendCodeWith:(NSIndexPath *)index{
    [[[LoginStore alloc]init] sendCodeWithTelephoneNumber:self.phoneName Success:^(id  _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            addAdressCell *cell = [self.tableView cellForRowAtIndexPath:index];
            [cell daojishi];
            self.realCode = res[@"data"][@"code"];
            self.realPhone = self.phoneName;
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    addAdressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addAdressCellID"];
    cell.detailtext.clearButtonMode = UITextFieldViewModeWhileEditing;
    cell.rightarrow.hidden = YES;
    if (indexPath.row == 0) {
        cell.subtitle.text = @"姓名";
        cell.detailtext.placeholder = @"请输入真实姓名";
    }else if (indexPath.row == 1) {
        cell.subtitle.text = @"手机号";
        cell.detailtext.placeholder = @"请输入手机号";
    }else if (indexPath.row == 2) {
        cell.detailtext.clearButtonMode = UITextFieldViewModeNever;
        cell.subtitle.text = @"验证码";
        cell.detailtext.placeholder = @"输入验证码";
        cell.sendbutton.hidden = NO;
        [cell.sendbutton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cell setSendBlock:^{
            if ([self.phoneName isVaildMobileNo]) {
                [self sendCodeWith:indexPath];
            }else{
                [self showMBPError:@"请输入正确的手机号"];
            }
        }];
    }else if (indexPath.row == 3) {
        cell.subtitle.text = @"密码";
        cell.detailtext.secureTextEntry = YES;
        cell.detailtext.placeholder = @"请输入密码";
    }else if (indexPath.row == 4) {
        cell.subtitle.text = @"确认";
        cell.detailtext.secureTextEntry = YES;
        cell.detailtext.placeholder = @"请再次输入密码";
    }
    [cell setDetailBlock:^(NSString * _Nonnull str) {
        if (indexPath.row == 0) {
            self.realname = str;
            self.userName = str;
        }else if (indexPath.row == 1) {
            self.phoneName = str;
        }else if (indexPath.row == 2) {
            self.code = str;
        }else if (indexPath.row == 3) {
            self.passWord = str;
        }else if (indexPath.row == 4) {
            self.rePassWord = str;
        }
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
@end
